package com.lancoo.znbkxx.teacher.aibkTestCoach.studyAnalysis

import android.graphics.Color
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.*
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.bindLifeCycle
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.StuPaperTypeName
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.viewModel.StuStudyAnalysisViewModel
import com.lancoo.znbkxx.teacher.databinding.ActivityStudyAnalysisStuBinding
import com.lancoo.znbkxx.teacher.ui.Presenter
import com.lancoo.znbkxx.teacher.utils.ToastUtils
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * Created by Dadong on 2021/1/26
 * Describe:
 */
public class StuStudyAnalysisActivity : KBaseActivity(), Presenter {
    private lateinit var mBinding: ActivityStudyAnalysisStuBinding
    private val mViewModel: StuStudyAnalysisViewModel by viewModel()
    private lateinit var statisticAdapter: StuStatisticAdapter
    private lateinit var instructAdapter: StuInstructAdapter
    private var statisticData: MutableList<String> = ArrayList()
    private var instructData: MutableList<StuPaperTypeName> = ArrayList()
    private val barEntries = mutableListOf<BarEntry>()
    private val lineEntries = mutableListOf<Entry>()
    private val xLabels = mutableListOf<String>()
    private val classXLabels = mutableListOf<String>()
    private val barEntriesPerson = mutableListOf<BarEntry>()
    private val barEntriesClass = mutableListOf<BarEntry>()
    private var stuId = ""

    override fun setLayout(): Int {
        return R.layout.activity_study_analysis
    }

    override fun initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_study_analysis_stu)
        mBinding.presenter = this
        mBinding.vm = mViewModel
        mBinding.acvAnalysis.setData(floatArrayOf(80f, 20f, 40f, 50f, 60f, 70f))
        mBinding.tvAll.background = resources.getDrawable(R.drawable.bg_rect_blue)
        mBinding.tvAll.setTextColor(resources.getColor(R.color.c0099ff))
    }

    private fun initRvStatistic() {
        statisticAdapter = StuStatisticAdapter(R.layout.item_study_analysis_statistic, statisticData)
        mBinding.rvStatistic.layoutManager = GridLayoutManager(this, 3)
        mBinding.rvStatistic.adapter = statisticAdapter
    }


    override fun initData() {
        stuId = intent.extras?.getString("stuId", "").toString()
        getClassLearningAnalysis()
        getWeekClassLearningAnalysis()
        getMonthClassLearningAnalysis()
    }

    private fun getClassLearningAnalysis() {
        mViewModel.getClassLearningAnalysis(stuId)
                .doOnSubscribe {
                    startLoad()
                }.bindLifeCycle(this)
                .subscribe({
                    stopLoad()
                    statisticData = mViewModel.getStatisticData()
                    initRvStatistic()
                    instructData = mViewModel.studyAnalysisInfo.get()!!.StuPaperAnswerDetail.PaperTypeNameList
                    getAcvAnalysis()
                    getClassChart()
                    getScoringRateChart(-1)
                },
                        {
                            stopLoad()
                            MyToast.showToast(it.message)
                        })
    }

    private fun getWeekClassLearningAnalysis() {
        mViewModel.getWeekClassLearningAnalysis(stuId)
                .doOnSubscribe {
                }.bindLifeCycle(this)
                .subscribe({
                },
                        {})
    }

    private fun getMonthClassLearningAnalysis() {
        mViewModel.getMonthClassLearningAnalysis(stuId)
                .doOnSubscribe {
                }.bindLifeCycle(this)
                .subscribe({
                },
                        {})
    }

    private fun getAcvAnalysis() {
        mBinding.acvAnalysis.setData(floatArrayOf(
                mViewModel.studyAnalysisInfo.get()!!.StuPaperAnswerDetail.PaperTypeNameList[0].Rate.toFloat(),
                mViewModel.studyAnalysisInfo.get()!!.StuPaperAnswerDetail.PaperTypeNameList[1].Rate.toFloat(),
                mViewModel.studyAnalysisInfo.get()!!.StuPaperAnswerDetail.PaperTypeNameList[2].Rate.toFloat(),
                mViewModel.studyAnalysisInfo.get()!!.StuPaperAnswerDetail.PaperTypeNameList[3].Rate.toFloat(),
                mViewModel.studyAnalysisInfo.get()!!.StuPaperAnswerDetail.PaperTypeNameList[4].Rate.toFloat(),
                mViewModel.studyAnalysisInfo.get()!!.StuPaperAnswerDetail.PaperTypeNameList[5].Rate.toFloat(),
                mViewModel.studyAnalysisInfo.get()!!.StuPaperAnswerDetail.PaperTypeNameList[6].Rate.toFloat()))
        instructAdapter = StuInstructAdapter(R.layout.item_study_analyisis_instruct, instructData)
        mBinding.rvAnalysis.layoutManager = LinearLayoutManager(this)
        mBinding.rvAnalysis.adapter = instructAdapter
    }


    private fun getScoringRateChart(isWeek: Int) {
        val paperlist =
                if (isWeek == 0) {
                    mViewModel.weekStudyAnalysisInfo.get()!!.StuPaperAnswerDetail.PaperList
                } else if (isWeek == 1) {
                    mViewModel.monthStudyAnalysisInfo.get()!!.StuPaperAnswerDetail.PaperList
                } else {
                    mViewModel.studyAnalysisInfo.get()!!.StuPaperAnswerDetail.PaperList
                }
        if (paperlist.size == 0) {
            mBinding.chartScoring.visibility = View.GONE
            mBinding.ivEmpty.visibility = View.VISIBLE
        } else {
            mBinding.chartScoring.visibility = View.VISIBLE
            mBinding.ivEmpty.visibility = View.GONE
        }
        barEntries.clear()
        lineEntries.clear()
        xLabels.clear()
        paperlist.forEachIndexed { index, paper ->
            val barEntry = BarEntry(index.toFloat(), paper.ScoreRate.toFloat() * 100)
            barEntries.add(barEntry)
            lineEntries.add(barEntry)
            var name = paper.PaperName.substring(paper.PaperName.indexOf("（") + 1, paper.PaperName.indexOf("）"));
            xLabels.add(name)
        }

        mBinding.chartScoring.apply {
            isDragEnabled = true
            val barDataSet = BarDataSet(barEntries, "")
            val colors = ArrayList<Int>()
            colors.add(Color.parseColor("#22d7bb"))
            colors.add(Color.parseColor("#ffcd80"))
            barDataSet.colors = colors
            val barData = BarData(barDataSet)
            barData.apply {
                setDrawValues(false)
                setValueTextColor(Color.parseColor("#22d7bb"))
                setValueTextSize(13f)
                barWidth = 0.23f
            }
            val lineDataSet = LineDataSet(lineEntries, "")
            lineDataSet.apply {
                color = Color.parseColor("#2dbcff")
                lineWidth = 2f
                setDrawCircleHole(false)
                setDrawCircles(false)
                mode = LineDataSet.Mode.LINEAR
            }
            val lineData = LineData(lineDataSet)
            lineData.setDrawValues(false)
            val combinedData = CombinedData()
            combinedData.setData(barData)
            combinedData.setData(lineData)
            data = combinedData
            axisLeft.apply {
                spaceBottom = 0f
                axisMinimum = 0f
                axisMaximum = 100f
                textSize = 10f
                textColor = Color.parseColor("#999999")
            }

            axisRight.isEnabled = false
            //关闭图例
            legend.isEnabled = false
            //关闭描述信息的显示
            description.isEnabled = false
            setPinchZoom(false)
            setScaleEnabled(false)
            //设置x轴显示在下方
            xAxis.apply {
                axisMinimum = -0.5f
                axisMaximum = if (paperlist.size < 5) 5f else paperlist.size.toFloat()
                position = XAxis.XAxisPosition.BOTTOM
                isGranularityEnabled = true
                granularity = 1f
                labelCount = xLabels.size
                //设置X轴文本旋转角度
//                labelRotationAngle = 7f
                setDrawAxisLine(false)
                setDrawGridLines(false)
                //设置X轴文本大小
                textSize = 7f
                textColor = Color.parseColor("#999999")
                valueFormatter = IndexAxisValueFormatter(xLabels) //设置x轴标签格式化器
            }
            setVisibleXRangeMaximum(5f)
            animateXY(1000, 1000)
        }
    }

    private fun getClassChart() {
        barEntriesPerson.clear()
        barEntriesClass.clear()
        classXLabels.clear()
        val groupSpace = 0.4f
        val barSpace = 0.02f
        val barWidth = 0.3f
        val qTypeScoreRateList = mViewModel.studyAnalysisInfo.get()!!.StuQuesTypeAnalysis.QTypeScoreRateList
        xLabels.add("")
        qTypeScoreRateList.forEachIndexed { index, qTypeScoreRate ->
            val barEntryPerson = BarEntry(index.toFloat() + 0.5f, qTypeScoreRate.TrastAvgRate.toFloat() * 100)
            val barEntryClass = BarEntry(index.toFloat() + 0.5f,
                    qTypeScoreRate.MainAvgRate.toFloat() * 100)
            barEntriesPerson.add(barEntryPerson)
            barEntriesClass.add(barEntryClass)
            val name = qTypeScoreRate.GenreName
            xLabels.add(name)
        }

        mBinding.chartClassScoring.apply {
            val barDataSetPerson = BarDataSet(barEntriesPerson, "")
            barDataSetPerson.color = Color.parseColor("#22d7bb")
            val barDataSetClass = BarDataSet(barEntriesClass, "")
            barDataSetClass.color = Color.parseColor("#2dbcff")

            val barData = BarData(barDataSetPerson, barDataSetClass)
            barData.setDrawValues(false) //是否显示柱子的数值
            barData.barWidth = barWidth  //每个柱子的宽度
            this.data = barData
            axisLeft.apply {
                isEnabled = true
                setDrawGridLines(true)
                setDrawAxisLine(true)
                setDrawLabels(true)
                spaceBottom = 0f
                axisMinimum = 0f
                axisMaximum = 100f
                textSize = 10f
                textColor = Color.parseColor("#999999")
            }
            axisRight.isEnabled = false
            //关闭图例
            legend.isEnabled = false
            //关闭描述信息的显示
            description.isEnabled = false
            setPinchZoom(false)
            setScaleEnabled(false)
            //设置x轴显示在下方
            xAxis.apply {
                axisMinimum = 0f
                axisMaximum = if (qTypeScoreRateList.size < 5) 5f else (qTypeScoreRateList.size.toFloat() + 1)
                position = XAxis.XAxisPosition.BOTTOM
                labelCount = qTypeScoreRateList.size + 1
                if (xLabels.size > 5)
                    labelRotationAngle = 60f
                isGranularityEnabled = true
                setDrawAxisLine(false)
                setDrawGridLines(false)
                setCenterAxisLabels(false);
                granularity = 1f
                //设置X轴文本大小
                textSize = 11f
                textColor = Color.parseColor("#999999")
                valueFormatter = IndexAxisValueFormatter(xLabels) //设置x轴标签格式化器
            }
            groupBars(0f, groupSpace, barSpace)
            animateXY(1000, 1000)
        }
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.sbtn_back -> {
                finish()
            }
            R.id.tv_week -> {
                getScoringRateChart(0)
                mBinding.tvWeek.background = resources.getDrawable(R.drawable.bg_rect_blue)
                mBinding.tvMonth.background = resources.getDrawable(R.drawable.bg_rect_gray)
                mBinding.tvAll.background = resources.getDrawable(R.drawable.bg_rect_gray)
                mBinding.tvWeek.setTextColor(resources.getColor(R.color.c0099ff))
                mBinding.tvMonth.setTextColor(resources.getColor(R.color.c888888))
                mBinding.tvAll.setTextColor(resources.getColor(R.color.c888888))
            }
            R.id.tv_month -> {
                getScoringRateChart(1)
                mBinding.tvWeek.background = resources.getDrawable(R.drawable.bg_rect_gray)
                mBinding.tvMonth.background = resources.getDrawable(R.drawable.bg_rect_blue)
                mBinding.tvAll.background = resources.getDrawable(R.drawable.bg_rect_gray)
                mBinding.tvWeek.setTextColor(resources.getColor(R.color.c888888))
                mBinding.tvMonth.setTextColor(resources.getColor(R.color.c0099ff))
                mBinding.tvAll.setTextColor(resources.getColor(R.color.c888888))
            }
            R.id.tv_all -> {
                getScoringRateChart(-1)
                mBinding.tvWeek.background = resources.getDrawable(R.drawable.bg_rect_gray)
                mBinding.tvMonth.background = resources.getDrawable(R.drawable.bg_rect_gray)
                mBinding.tvAll.background = resources.getDrawable(R.drawable.bg_rect_blue)
                mBinding.tvWeek.setTextColor(resources.getColor(R.color.c888888))
                mBinding.tvMonth.setTextColor(resources.getColor(R.color.c888888))
                mBinding.tvAll.setTextColor(resources.getColor(R.color.c0099ff))
            }
        }
    }

    override fun onCancel(view: View?) {
    }
}